package com.roc.service.impl;

import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.alibaba.fastjson.JSONObject;
import com.roc.bean.ScanCodeAudit;
import com.roc.bean.YYCardBean;
import com.roc.dao.DaoException;
import com.roc.dao.IBaseDao;
import com.roc.dao.ISQLBaseDao;
import com.roc.newPage.IPageDao;
import com.roc.pojo.MessageSend;
import com.roc.pojo.Operators;
import com.roc.pojo.ScanCodeDictionary;
import com.roc.pojo.TblMchtBankAccount;
import com.roc.pojo.TblMchtContact;
import com.roc.pojo.TblMchtInf;
import com.roc.pojo.TblMchtInfSm;
import com.roc.pojo.TblMchtPicture;
import com.roc.service.IYYCardService;
import com.roc.service.ServiceException;
import com.roc.util.Constance;
import com.roc.util.Utils;
import com.roc.util.constant.SysLogType;
import com.roc.util.httpUtil.HttpClientUtil;
@Service
@Transactional
public class YYCardServiceImpl implements IYYCardService {
	static Logger logger=LogManager.getLogger(YYCardServiceImpl.class);
	
	@Autowired
	private ISQLBaseDao sqlBaseDao;
	@Autowired
	private IBaseDao baseDao;
	@Autowired
	private IPageDao  pageDao;
	
	@Override
	public List<Map<String, Object>> categoryFirstType(String stairname,String moversname) {
		List<Map<String,Object>> listMap=new ArrayList<Map<String,Object>>();
		Object[] parmas=new Object[2];
		parmas[0]=stairname;
		parmas[1]=moversname;
		String sql="select flyersname,categoryid from t_pa_category where stairname=? and moversname=?";
		logger.info("加载商户三级目录");		
		try {
			List<Object> list=sqlBaseDao.queryAll(sql, parmas);
			if(list!=null&&list.size()>0)
			{
				for(int i=0;i<list.size();i++)
				{
					Map<String, Object> map=new HashMap<String, Object>();
					Object[] object=(Object[]) list.get(i);
					map.put("flyersname", String.valueOf(object[0]));
					map.put("categoryid", String.valueOf(object[1]));
					listMap.add(map);
				}
			}
			logger.info("加载三级商户类目");
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return listMap;
	}
	@Override
	public List<Map<String, Object>> categoryFirstType() {
		String sql="select stairname from t_pa_category group by stairname";
		List<Map<String, Object>> list=null;
		try {
			list=sqlBaseDao.querySqlToMap(sql);
			logger.info("加载一级商户类目");
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return list;
	}
	@Override
	public List<Map<String, Object>> categoryFirstType(String stairname) {
		Object[] parmas=new Object[1];
		parmas[0]=stairname;
		String sql="select moversname from t_pa_category where stairname=? group by moversname";
		List<Map<String, Object>> listMap=new ArrayList<Map<String,Object>>();
		try {
			List<Object> list=sqlBaseDao.queryAll(sql, parmas);
			if(list!=null&&list.size()>0)
			{
				for(int i=0;i<list.size();i++)
				{
					Map<String, Object> map=new HashMap<String, Object>();
					Object object=list.get(i);
					map.put("moversname", String.valueOf(object));
					listMap.add(map);
				}
			}
			logger.info("加载二级商户类目");
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return listMap;
	}
	@Override
	public boolean sendMsg(String phone,String realCode) throws ServiceException {
		try {
			String msgText="验证码:"+realCode+"，尊敬的付临门用户，此验证码只用于开通一一卡，请勿泄露";
			MessageSend ms = new MessageSend();
			ms.setPhoneNumber(phone);
			ms.setMesContent(msgText);
			ms.setSendFlag("0");
			ms.setDtCreate(new Date());
			ms.setTimes(0);
			baseDao.edit(ms);
			logger.info("向短信跑批表插入数据成功");
			return true;
		} catch (Exception e) {
			logger.error("向短信跑批表插入数据失败", e);
            return false;
		}
	}
	@Override
	public TblMchtContact findScanCodeExist(String mchtNo) throws ServiceException {
		TblMchtContact tblMchtContact=null;
		try {
			Object[] parmas=new Object[2];
			parmas[0]=mchtNo;
			parmas[1]="1";
			String scanCodeSql="select s.mchtcd,s.localmchtcd,s.outmchtcd,s.channelid,s.status,s.remark1,s.remark2,s.remark3 from apstfr.tbl_mcht_contact s where s.mchtcd=? and s.status=?";
			Object object=sqlBaseDao.findObj(scanCodeSql, parmas);
			if(object!=null){
				Object[] obj=(Object[]) object;
				tblMchtContact=new TblMchtContact();
				tblMchtContact.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				tblMchtContact.setLocalMchtCd(Constance.Null2EmptyTrim(obj[1]));
				tblMchtContact.setOutMchtCd(Constance.Null2EmptyTrim(obj[2]));
				tblMchtContact.setChannelId(Constance.Null2EmptyTrim(obj[3]));
				tblMchtContact.setStatus(Constance.Null2EmptyTrim(obj[4]));
				tblMchtContact.setRemark1(Constance.Null2EmptyTrim(obj[5]));
				tblMchtContact.setRemark2(Constance.Null2EmptyTrim(obj[6]));
				tblMchtContact.setRemark3(Constance.Null2EmptyTrim(obj[7]));
			}
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询支付宝/微信扫码是否开通失败~");
		}
		return tblMchtContact;
	}
	@Override
	public Map<String, Object> sendScanCodeMessage(TblMchtInf tblMchtInf,
			YYCardBean yyCardBean,Operators op) throws ServiceException {
		String sql=" MERGE INTO APSTFR.TBL_MCHT_CONTACT A USING (SELECT ? AS MCHTCD FROM DUAL) B ON (A.MCHTCD=B.MCHTCD) "
				+ "WHEN NOT MATCHED THEN INSERT(A.MCHTCD,A.LOCALMCHTCD,A.OUTMCHTCD,A.CHANNELID,A.STATUS,A.REMARK1,A.REMARK2,A.REMARK3,A.REMARK4) VALUES(?,?,?,?,?,?,?,?,?)";
		String auditsql=" MERGE INTO T_WX_AUDIT A USING (SELECT ? AS MCHT_CD FROM DUAL) B ON (A.MCHT_CD=B.MCHT_CD) "
				+ "WHEN NOT MATCHED THEN INSERT(A.MCHT_CD,A.LOCAL_MCHT,A.OUT_MCHT,A.WX_SUBID,A.STATUS,A.DT_CREATE,A.REMARK1,A.REMARK2,A.REMARK3) "
				+ "VALUES(?,?,?,?,?,SYSDATE,?,?,?)";
		List<Object> parmas=new ArrayList<Object>();
		List<Object> auditParmas=new ArrayList<Object>();
		Map<String, Object> map=new HashMap<String, Object>();
		String msg="商户已绑卡",status="";
		try {
				TblMchtContact contact=findScanCodeExist(tblMchtInf.getId());
				if(contact==null){
					JSONObject json=new JSONObject();
					String orgCode=null;//机构号
					String groupCd=tblMchtInf.getGroupCD();
					if("2".equals(Constance.Null2EmptyTrim(groupCd))){
						logger.info("当前商户为直营商户");
						orgCode=Utils.getConfigValue("org_code_zy");
					}else{
						logger.info("当前商户为非直营商户");
						orgCode=Utils.getConfigValue("org_code");
					}
					json.put("EXT_ORG_NO",orgCode);//机构号
					json.put("TRADE_CODE", "PASM05");//交易代码
					json.put("TX_OUT_CHANNEL", "WZPA");//支付渠道
					json.put("TX_PAY_TYPE", "PA041");//交易类型
					Random r = new Random();
					int randomThr = 10000 + r.nextInt(89999);
					String localMchtCd=String.valueOf(randomThr)+tblMchtInf.getId();
					json.put("TX_EXTERNAL_ID",localMchtCd);//本地商户唯一ID
					json.put("TX_NAME", tblMchtInf.getName());//名称
					json.put("TX_ALIAS_NAME", tblMchtInf.getNameBusi());//简称
					json.put("TX_SERVICE_PHONE", "4006078866");//客服电话
					//json.put("TX_CONTACT_NAME",Constance.Null2EmptyTrim(yyCardBean.getWxName()));//联系人
					json.put("TX_CONTACT_NAME",tblMchtInf.getContactName());//联系人
					json.put("TX_CONTACT_MOBILE", tblMchtInf.getContactPhoneNo());//联系手机号
					json.put("TX_CATEGORY_ID", Constance.Null2EmptyTrim(yyCardBean.getCategoryId()));
					json.put("TX_CONTACT_EMAIL","kf@yjpal.com");//联系邮箱
					json.put("TX_MEMO","");//商户备注
					if("1".equals(tblMchtInf.getDvpBy())){//非法人结算
						json.put("TX_ID_CARD_NAME", tblMchtInf.getContactName());//身份证姓名
						json.put("TX_ID_CARD_NUM", tblMchtInf.getStlmWayDesc());//身份证号码						
					}else{//法人结算
						json.put("TX_ID_CARD_NAME", tblMchtInf.getCertif());//身份证姓名
						json.put("TX_ID_CARD_NUM", tblMchtInf.getCertifNo());//身份证号码	
					}
					json.put("TX_STORE_ADDRESS", tblMchtInf.getRegAddr());//店铺地址
					json.put("TX_ID_CARD_HAND_IMG_URL",tblMchtInf.getPictrueList().get(0).getUrl());//手持身份证图片
					json.put("TX_STORE_FRONT_IMG_URL",tblMchtInf.getPictrueList().get(1).getUrl());//商户门头图片
					json.put("TX_BIZ_LICENSE_IMG_URL",tblMchtInf.getPictrueList().get(2).getUrl());//营业执照图片
					json.put("TX_PROVINCE", tblMchtInf.getProvCd());//省份
					json.put("TX_CITY", tblMchtInf.getCityCd());//城市
					json.put("TX_DISTRICT", tblMchtInf.getAreaCd());//区县
					//json.put("TX_CONTACT_WXID",Constance.Null2EmptyTrim(yyCardBean.getWx()));//微信号
					logger.info("商户入驻请求报文:"+json.toJSONString());
					String settleIn=HttpClientUtil.httpPost(Utils.getConfigValue("url_scanCode"),json);
					logger.info("商户入驻应答报文:"+settleIn);
					JSONObject response=JSONObject.parseObject(settleIn);
					if("00".equals(response.getString("MSG_CODE"))){
						//绑卡
						logger.info("商户入驻成功,进行绑卡操作");
						String outMchtCd=response.getString("SUB_MERCHANT_ID");//入驻商户号
						//处理支付宝
						msg="支付宝入驻";
						String zfb_status="";
						if(response.containsKey("ZFB_STATUS")){
							zfb_status="1";
							msg=msg+"成功";
						}else{
							zfb_status="0";
							msg=msg+"失败";
						}
						//处理微信
						String wxSubidAudit="";//微信子商户号
						msg=msg+",微信入驻";
						String wx_Status="0";
						//....
						JSONObject jsonBind=new JSONObject();
						jsonBind.put("EXT_ORG_NO",orgCode);//机构号
						jsonBind.put("TRADE_CODE","PASM05");//交易代码
						jsonBind.put("TX_OUT_CHANNEL", "WZPA");//支付渠道
						jsonBind.put("TX_PAY_TYPE", "PA006");//交易类型
						jsonBind.put("TX_SUB_MERCHANT_ID",outMchtCd);//入驻成功返回的商户号
						jsonBind.put("TX_BANK_CRAD_NO","36610188000159148");//持卡卡号
						jsonBind.put("TX_CARD_HOLDER","德颐支付");//持卡人姓名
						logger.info("商户绑卡请求报文:"+json.toJSONString());
						String bindCard=HttpClientUtil.httpPost(Utils.getConfigValue("url_scanCode"),jsonBind);
						logger.info("商户绑卡应答报文:"+bindCard);
						JSONObject responseCard=JSONObject.parseObject(bindCard);
						if("00".equals(responseCard.getString("MSG_CODE")) && "true".equals(responseCard.getString("BIND_FLAG"))){
							logger.info("商户绑卡成功");
							//尝试去开通微信
							logger.info("尝试去开通微信");
							Map<String,String> wxMap=new HashMap<String, String>();
							wxMap.put("orgCode",orgCode);//机构
							wxMap.put("sub_id",outMchtCd);//入驻商户号
							wxMap.put("transType","PA042");
							String wxResponse=queryEnterInfo(wxMap);
							JSONObject WXresponseJson=JSONObject.parseObject(wxResponse);
							if("00".equals(WXresponseJson.get("MSG_CODE"))){
								if(WXresponseJson.get("WX_SUBID")==null){
									wx_Status="0";//微信子商户入驻失败
									msg=msg+"失败";
								}else{
									wxSubidAudit=WXresponseJson.getString("WX_SUBID");
									if("2".equals(Constance.Null2EmptyTrim(WXresponseJson.get("WX_CONFIG_STATUS")))){
										wx_Status="1";//全部成功
										msg=msg+"成功";
									}else if("1".equals(Constance.Null2EmptyTrim(WXresponseJson.get("WX_CONFIG_STATUS")))){
										wx_Status="2";//部分成功
										msg=msg+"子商户配置未完成,请重新尝试";
									}
									else if(WXresponseJson.get("WX_CONFIG_STATUS")==null){
										wx_Status="3";//微信子商户配置失败
										msg=msg+"子商户配置失败,请尝试重新入驻";
									}						
								}
							}else{
								wx_Status="0";
								msg=msg+"失败,"+WXresponseJson.getString("MSG_TXT");
							}
							//添加到核心表
							logger.info("添加到核心信息");
							parmas.add(tblMchtInf.getId());
							parmas.add(tblMchtInf.getId());
							parmas.add(localMchtCd);
							parmas.add(outMchtCd);
							parmas.add("1");//渠道
							parmas.add("1");//状态成功
							parmas.add(orgCode);//机构号
							parmas.add(zfb_status);//支付宝标识
							parmas.add(wx_Status);//微信标识
							parmas.add(Constance.Null2EmptyTrim(yyCardBean.getCategoryId())); //所属行业
							int rows=sqlBaseDao.deleteBySql(sql, parmas);
							if(rows>0){
								//添加到微信审核表
								logger.info("添加到微信审核表..");
								auditParmas.add(tblMchtInf.getId());
								auditParmas.add(tblMchtInf.getId());
								auditParmas.add(localMchtCd);
								auditParmas.add(outMchtCd);
								auditParmas.add(wxSubidAudit);
								String flag_audit="EE";
								if(!"".equals(wxSubidAudit) && "1".equals(wx_Status)){
									flag_audit="SS";
								}
								auditParmas.add(flag_audit);
								auditParmas.add(tblMchtInf.getProvCd()); //省
								auditParmas.add(tblMchtInf.getCityCd()); //市
								auditParmas.add(tblMchtInf.getAreaCd()); //区
								sqlBaseDao.deleteBySql(auditsql, auditParmas);
								//插入图片信息
								logger.info("添加到图片信息..");
								status="success";
								baseDao.addSyslog(SysLogType.SCANCODE_HANDLE.getCode(),SysLogType.SCANCODE_HANDLE.getName() ,op.getAccountNo(),"商户【"+tblMchtInf.getId()+"】入驻绑卡成功,入驻机构号["+orgCode+"]");
								for(TblMchtPicture p:tblMchtInf.getPictrueList()){
									TblMchtPicture pictrue=new TblMchtPicture();
									pictrue.setMchtCd(tblMchtInf.getId());
									pictrue.setUrl(p.getUrl());
									pictrue.setPindex(1);//顺序默认
									
									Random ra=new Random();
									int random=1000+ra.nextInt(8999);
									int first=p.getUrl().trim().indexOf("mid=")+4;
									int sencond=p.getUrl().trim().lastIndexOf("&");
									if(first>4 && sencond>0){
										pictrue.setFileName(pictrue.getUrl().substring(first, sencond));//名称
										pictrue.setPcode(pictrue.getFileName().substring(0, pictrue.getFileName().indexOf(".")));//拆封名称去掉后缀
										pictrue.setFileId("FILE_ID"+pictrue.getFileName().substring(0, pictrue.getFileName().indexOf("."))+"_"+random);//主键id
									}else{
										String b=p.getUrl().trim().substring(p.getUrl().lastIndexOf("&")+1);
										pictrue.setPcode("code");//拆封名称去掉后缀
										pictrue.setFileName(b);//名称
										pictrue.setFileId("FILE_ID"+pictrue.getFileName());//主键id
									}
									pictrue.setDocType("SM");
									pictrue.setSystemflag("00");
									pictrue.setStatus("0");
									pictrue.setRecOprId("I");//插入操作
									pictrue.setRecCrtTs(new Timestamp(System.currentTimeMillis()));
									pictrue.setRecUpdOpr(String.valueOf(op.getId()));//操作员id
									baseDao.editSave(pictrue);
								}
							}
						}else{
							msg="商户绑卡失败,"+responseCard.getString("MSG_TXT");
						}
					}else{
						msg="商户入驻失败,"+response.getString("MSG_TXT");
					}
				}				
				map.put("message", msg);
				map.put("status", status);
				logger.info(msg);
			} catch (Exception e) {
				logger.debug(e.getMessage());
				throw new ServiceException("发送报文失败");
			}			
			return map;
	}
	
	
	@Transactional(readOnly=true)
	public TblMchtInf queryMerinfoInfoById(String merinfoNo)
			throws ServiceException {
		TblMchtInf merinfo=null;
		Object[] param={merinfoNo};
		try {
			if(null==merinfoNo) return  merinfo; //为空返回
			//商户信息
			String mer_hql=" from TblMchtInf t where t.id=?";
			merinfo=(TblMchtInf)pageDao.createQueryUniqueResult(mer_hql,param );
			//结算信息
			String settle_hql="from TblMchtBankAccount t where t.ownerCd=?";
			TblMchtBankAccount bankAccount=(TblMchtBankAccount)pageDao.createQueryUniqueResult(settle_hql,param );
			merinfo.setBankAccount(bankAccount);//SET 结算信息					
			return  merinfo;
			} catch (DaoException e) {
			 	logger.error(e.getMessage(),e);
			 	throw new ServiceException(e.getMessage(),e);
			}
	}

	@Override
	public List<ScanCodeDictionary> findDicnationary(String code)
			throws ServiceException {
		List<ScanCodeDictionary> listMap=new ArrayList<ScanCodeDictionary>();
		Object[] parmas=new Object[1];
		parmas[0]=code;
		String sql="select code,name from t_scan_code_dictionary where pcode=?";
		try {
			List<Object> list=sqlBaseDao.queryAll(sql, parmas);
			if(list!=null&&list.size()>0)
			{
				for(int i=0;i<list.size();i++)
				{
					ScanCodeDictionary dic=new ScanCodeDictionary();
					Object[] object=(Object[]) list.get(i);
					dic.setCode(String.valueOf(object[0]));
					dic.setName(String.valueOf(object[1]));
					listMap.add(dic);
				}
			}
			logger.info("加载省市县子级");
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return listMap;
	}
	
	protected String queryEnterInfo(Map<String,String> map){
		//transType 取值 PA042(微信子商户入驻)  PA044(支付宝入驻) PA043(微信子商户配置) PA048(修改入驻商户信息)
		String transType=map.get("transType");
		JSONObject queryJson=new JSONObject();
		queryJson.put("EXT_ORG_NO",map.get("orgCode"));//机构
		queryJson.put("TRADE_CODE","PASM05");//交易代码
		queryJson.put("TX_OUT_CHANNEL","WZPA");//支付渠道
		queryJson.put("TX_PAY_TYPE",transType);//交易类型
		queryJson.put("TX_SUB_MERCHANT_ID",map.get("sub_id"));//入驻成功返回商户号
		if("PA048".equals(transType)){//修改必填
			queryJson.put("TX_CONTACT_NAME", map.get("name"));//联系人姓名
			queryJson.put("TX_CONTACT_WXID", "");//联系人微信号id
		}
		else if("PA043".equals(transType)){//微信子商户配置
			if("3".equals(map.get("flag"))){
				queryJson.put("TX_JSAPI_PATH", Utils.getConfigValue("jsapi_path"));//微信JSAPI路径
			}else if("2".equals(map.get("flag"))){
				queryJson.put("TX_SUB_APPID", Utils.getConfigValue("sub_appid"));//微信公众号id
			}
			
		}
		logger.info("["+map.get("sub_id")+"]:["+transType+"]请求报文:"+queryJson.toJSONString());
		String queryJsonString=HttpClientUtil.httpPost(Utils.getConfigValue("url_scanCode"),queryJson);
		logger.info("["+map.get("sub_id")+"]:["+transType+"]返回报文:"+queryJsonString);
		return queryJsonString;
	}

	@Override
	public Map<String, Object> openCardAgain(TblMchtInf tblMchtInf,
			YYCardBean yyCardBean, Operators op, String type)
			throws ServiceException {
		Map<String, Object> result=new HashMap<String, Object>();
		List<Object> parmas=new ArrayList<Object>();
		String msg="",status="";		
		String sql="update apstfr.tbl_mcht_contact s set s.remark2=?,s.remark3=? where s.mchtcd=?";
		try {
			TblMchtContact contact=findScanCodeExist(tblMchtInf.getId());
			if(contact!=null){
				String orgCode=null;//机构号
				String groupCd=tblMchtInf.getGroupCD();
				if("2".equals(Constance.Null2EmptyTrim(groupCd))){
					logger.info("当前商户为直营商户");
					orgCode=Utils.getConfigValue("org_code_zy");
				}else{
					logger.info("当前商户为非直营商户");
					orgCode=Utils.getConfigValue("org_code");
				}
				Map<String,String> map=new HashMap<String, String>();
				map.put("orgCode",orgCode);//机构
				map.put("sub_id", contact.getOutMchtCd());//入驻商户号
				String zfb_status="",wx_Status="",wxSubidAudit="";//微信子商户号
				if("0".equals(type)){//支付宝
					logger.info("支付宝重新入驻..");
					map.put("transType","PA044");
					String response=queryEnterInfo(map);
					JSONObject responseJson=JSONObject.parseObject(response);
					if("00".equals(responseJson.get("MSG_CODE"))){
						//处理支付宝
						msg="支付宝入驻";				
						if(responseJson.containsKey("ZFB_STATUS")){
							zfb_status="1";
							msg=msg+"成功";
						}else{
							zfb_status="0";
							msg=msg+"失败,请尝试重新入驻";
						}
						//更新数据
						status="success";
						parmas.add(zfb_status);
						parmas.add(contact.getRemark3());
						parmas.add(contact.getMchtCd());						
						sqlBaseDao.deleteBySql(sql, parmas);
					}else{
						msg=msg+"失败,"+responseJson.getString("MSG_TXT");
					}
				}else if("1".equals(type)){//微信
					Map<String,String> wxMap=new HashMap<String, String>();
					wxMap.putAll(map);
					wxMap.put("name",tblMchtInf.getContactName());
					wxMap.put("wx","");
					//判断微信在哪一步入驻失败，0微信子商户入驻失败，2微信子商户配置失败
					logger.info("校验微信入驻失败原因..");
					if("0".equals(contact.getRemark3())){//微信子商户入驻失败
						logger.info("优先修改原先入驻信息..");
						//优先修改原先入驻信息
						wxMap.put("transType", "PA048");
						String response=queryEnterInfo(wxMap);
						JSONObject responseJson=JSONObject.parseObject(response);
						if("00".equals(responseJson.get("MSG_CODE"))){
							String Uname=responseJson.getString("CONTACT_NAME");//返回的联系人名字							//校验是否修改完成
							logger.info("校验修改信息..");
							if(Uname.equals(wxMap.get("name"))){
									//进行入驻
									logger.info("微信重新入驻..");
									map.put("transType","PA042");
									String wxResponse=queryEnterInfo(map);
									JSONObject WXresponseJson=JSONObject.parseObject(wxResponse);
									if("00".equals(WXresponseJson.get("MSG_CODE"))){
										msg="微信入驻";
										if(WXresponseJson.get("WX_SUBID")==null){
											wx_Status="0";//微信子商户入驻失败
											msg=msg+"失败,请尝试重新入驻";
										}else{
											wxSubidAudit=WXresponseJson.getString("WX_SUBID");
											if("2".equals(Constance.Null2EmptyTrim(WXresponseJson.get("WX_CONFIG_STATUS")))){
												wx_Status="1";//全部成功
												msg=msg+"成功";
											}else if("1".equals(Constance.Null2EmptyTrim(WXresponseJson.get("WX_CONFIG_STATUS")))){
												wx_Status="2";//部分成功
												msg=msg+"子商户配置未完成,请重新尝试";
											}
											else if(WXresponseJson.get("WX_CONFIG_STATUS")==null){
												wx_Status="3";//微信子商户配置失败
												msg=msg+"子商户配置失败,请尝试重新入驻";
											}							
										}
										status="success";
										parmas.add(contact.getRemark2());
										parmas.add(wx_Status);
										parmas.add(contact.getMchtCd());						
										sqlBaseDao.deleteBySql(sql, parmas);
										//更新原审核信息
										String WX_update="UPDATE T_WX_AUDIT SET WX_SUBID=?,STATUS=?,Up_Create=SYSDATE WHERE MCHT_CD=? ";
										List<Object> auditParmas=new ArrayList<Object>();
										auditParmas.add(wxSubidAudit);
										String flag_audit="EE";//错误参数
										if(!"".equals(wxSubidAudit) && "1".equals(wx_Status)){
											flag_audit="SS";//扫码申请
											auditParmas.add(flag_audit);
										}else{
											WX_update="UPDATE T_WX_AUDIT SET WX_SUBID=?,Up_Create=SYSDATE WHERE MCHT_CD=? ";
										}
										auditParmas.add(tblMchtInf.getId());
										sqlBaseDao.deleteBySql(WX_update, auditParmas);
									}else{
										msg="微信入驻失败,"+WXresponseJson.getString("MSG_TXT");
									}
							}else{
								msg="校验修改信息失败，请尝试重新入驻";
							}
						}else{
							msg="修改原商户入驻信息失败,"+responseJson.getString("MSG_TXT");
						}					
					}else if("2".equals(contact.getRemark3())){//微信子商户配置失败
						logger.info("微信子商户配置支付subappid..");
						msg="微信子商户配置支付subappid";
						map.put("transType", "PA043");
						map.put("flag", "2");
						String response=queryEnterInfo(map);
						JSONObject responseJson=JSONObject.parseObject(response);
						if("00".equals(responseJson.get("MSG_CODE"))){
							String WX_SUBID=Constance.Null2EmptyTrim(responseJson.get("WX_SUBID"));
							String WX_CONFIG_STATUS=Constance.Null2EmptyTrim(responseJson.get("WX_CONFIG_STATUS"));
							if(!"".equals(WX_SUBID) && "2".equals(WX_CONFIG_STATUS)){
								status="success";
								parmas.add(contact.getRemark2());
								parmas.add("1");
								parmas.add(contact.getMchtCd());						
								sqlBaseDao.deleteBySql(sql, parmas);
								String sqlUP="UPDATE T_WX_AUDIT SET STATUS=?,Up_Create=SYSDATE WHERE MCHT_CD=? ";
								List<Object> auditParmas=new ArrayList<Object>();
								auditParmas.add("SS");
								auditParmas.add(tblMchtInf.getId());
								sqlBaseDao.deleteBySql(sqlUP, auditParmas);
								msg=msg+"成功";
							}else{
								msg=msg+"失败,请重新尝试";
							}
						}else{
							msg=msg+"失败,"+responseJson.getString("MSG_TXT");
						}
					}else if("3".equals(contact.getRemark3())){//微信子商户为空的情况
						logger.info("微信子商户配置支付授权目录..");
						msg="微信子商户配置参数";
						map.put("flag", "3");
						map.put("transType", "PA043");
						String response=queryEnterInfo(map);
						JSONObject responseJson=JSONObject.parseObject(response);
						if("00".equals(responseJson.get("MSG_CODE"))){
							if("1".equals(responseJson.getString("WX_CONFIG_STATUS"))){
								logger.info("微信子商户配置支付subappid..");
								map.put("flag", "2");
								String responseV=queryEnterInfo(map);
								JSONObject responseJsonV=JSONObject.parseObject(responseV);
								if("00".equals(responseJsonV.get("MSG_CODE"))){
									if("2".equals(responseJsonV.getString("WX_CONFIG_STATUS"))){
										wx_Status="1";
									}else{
										wx_Status="2";
									}
								}else{
									wx_Status="2";
								}
								status="success";
								parmas.add(contact.getRemark2());
								parmas.add(wx_Status);
								parmas.add(contact.getMchtCd());						
								sqlBaseDao.deleteBySql(sql, parmas);
								String sqlUP="UPDATE T_WX_AUDIT SET STATUS=?,Up_Create=SYSDATE WHERE MCHT_CD=? ";
								List<Object> auditParmas=new ArrayList<Object>();
								String flag_audit="EE";
								if("1".equals(wx_Status)){
									flag_audit="SS";
									auditParmas.add(flag_audit);
									auditParmas.add(tblMchtInf.getId());
									sqlBaseDao.deleteBySql(sqlUP, auditParmas);
								}								
							}else{
								msg=msg+"失败,请重新尝试";
							}
						}else{
							msg=msg+"失败,"+responseJson.getString("MSG_TXT");;
						}
					}
				}
			}else{
				msg="商户未入驻";
			}
			logger.info(msg);
			result.put("msg", msg);
			result.put("status", status);
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("发送报文失败");
		}
		return result;
	}
	@Override
	public Map<String,String> getWx(TblMchtInf tblMchtInf) throws ServiceException {
		Map<String,String> mapSHOW=new HashMap<String, String>();
		String orgCode=null,WX="",WXN="";//机构号
		String groupCd=tblMchtInf.getGroupCD();
		if("2".equals(Constance.Null2EmptyTrim(groupCd))){
			logger.info("当前商户为直营商户");
			orgCode=Utils.getConfigValue("org_code_zy");
		}else{
			logger.info("当前商户为非直营商户");
			orgCode=Utils.getConfigValue("org_code");
		}
		TblMchtContact contact=findScanCodeExist(tblMchtInf.getId());
		if(contact!=null && !contact.getRemark3().equals("0")){
			Map<String,String> map=new HashMap<String, String>();
			map.put("orgCode", orgCode);
			map.put("transType", "PA049");
			map.put("sub_id", contact.getOutMchtCd());
			String response=queryEnterInfo(map);
			JSONObject responseJson=JSONObject.parseObject(response);
			if("00".equals(responseJson.get("MSG_CODE"))){
				WX=responseJson.getString("CONTACT_WXID");
				WXN=responseJson.getString("CONTACT_NAME");
			}
			
		}
		mapSHOW.put("WX", WX);
		mapSHOW.put("WXN", WXN);
		return mapSHOW;
	}
	@Override
	public ScanCodeAudit queryAuditDetail(ScanCodeAudit audit)
			throws ServiceException {
		ScanCodeAudit aud=null;
		String querySql="select s.mcht_cd,t.name,s.wx_id,s.wx_name,s.wx_subid,s.status,s.up_create,s.counts from t_wx_audit s,tbl_mcht_inf t where s.mcht_cd=t.mcht_cd and  s.mcht_cd=? ";
		Object[] parmas=new Object[1];
		parmas[0]=audit.getMchtCd();
		try{
			Object object=sqlBaseDao.findObj(querySql, parmas);
			if(object!=null){
				Object[] obj=(Object[]) object;
				aud=new ScanCodeAudit();
				aud.setMchtCd(Constance.Null2EmptyTrim(obj[0]));
				aud.setName(Constance.Null2EmptyTrim(obj[1]));
				aud.setWxId(Constance.Null2EmptyTrim(obj[2]));
				aud.setWxName(Constance.Null2EmptyTrim(obj[3]));
				aud.setSubid(Constance.Null2EmptyTrim(obj[4]));
				aud.setStatus(Constance.Null2EmptyTrim(obj[5]));
				aud.setDate(Constance.Null2EmptyTrim(obj[6]));
				aud.setCounts(Constance.Null2EmptyTrim(obj[7]));
			}
		} catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("查询微信申请详细信息");
		}
		return aud;
	}
	@Override
	public synchronized Map<String, String> updateAudit(ScanCodeAudit audit,Operators op)
			throws ServiceException {
		String message="微信认证失败";
		Map<String, String> result=new HashMap<String,String>();
		String AuditSQL="update t_wx_audit set status=?,operators=?,up_create=sysdate,audit_opinion=?,counts=counts+1 where status='01' and mcht_cd=?";
		String UPSQL="update apstfr.tbl_mcht_contact  s set s.remark3=? where s.mchtcd=? and s.remark3='4'";
		List<Object> auditParams=new ArrayList<Object>();
		List<Object> Params=new ArrayList<Object>();
		String status="",wx_status="";
		if("1".equals(audit.getSymbol())){
			status="02";
			wx_status="1";
		}else if("0".equals(audit.getSymbol())){
			status="00";
			wx_status="0";
		}else{
			result.put("message", message);
			return result;
		}
		Params.add(wx_status);
		auditParams.add(status);
		auditParams.add(op.getAccountNo());
		auditParams.add(Constance.Null2EmptyTrim(audit.getAuditInfo()));
		Params.add(Constance.Null2EmptyTrim(audit.getMchtCd()));
		auditParams.add(Constance.Null2EmptyTrim(audit.getMchtCd()));
		try{
			int row=sqlBaseDao.deleteBySql(AuditSQL, auditParams);
			if(row>0){
				row=sqlBaseDao.deleteBySql(UPSQL, Params);
				if(row>0){
					message="认证成功";
					result.put("status", "success");
				}else{
					message="更新原申请开通微信扫码失败";
				}
			}else{
				message="该申请已被认证";
			}						
		}catch (DaoException e) {
			logger.debug(e.getMessage());
			throw new ServiceException("微信认证失败~!");
		}
		result.put("message", message);
		return result;
	}
	
	@Override
	public List<TblMchtInfSm> findMerForSma() throws ServiceException{
		List<TblMchtInfSm> merlist=new ArrayList<TblMchtInfSm>();
		String sql="select mcht_cd,name,name_busi,contact_name,contact_phone,category_id,certif,certif_no,reg_addr,"
				+ "pic_one,pic_two,pic_three,provcd,citycd,areacd,group_cd from tmp_sma ";
		try {
			List<Object> list=sqlBaseDao.queryAll(sql);
			if(list != null && list.size() > 0){
				Iterator iterator = list.iterator();
				while (iterator.hasNext()) {
					Object[] obj = (Object[]) iterator.next();
					TblMchtInfSm tblMchtInfSm = new TblMchtInfSm();
					tblMchtInfSm.setId(Constance.Null2EmptyTrim(obj[0]));
					tblMchtInfSm.setName(Constance.Null2EmptyTrim(obj[1]));
					tblMchtInfSm.setNameBusi(Constance.Null2EmptyTrim(obj[2]));
					tblMchtInfSm.setContactName(Constance.Null2EmptyTrim(obj[3]));
					tblMchtInfSm.setContactPhone(Constance.Null2EmptyTrim(obj[4]));
					tblMchtInfSm.setCategoryId(Constance.Null2EmptyTrim(obj[5]));
					tblMchtInfSm.setCertif(Constance.Null2EmptyTrim(obj[6]));
					tblMchtInfSm.setCertifNo(Constance.Null2EmptyTrim(obj[7]));
					tblMchtInfSm.setRegAddr(Constance.Null2EmptyTrim(obj[8]));
					tblMchtInfSm.setPicOne(Constance.Null2EmptyTrim(obj[9]));
					tblMchtInfSm.setPicTwo(Constance.Null2EmptyTrim(obj[10]));
					tblMchtInfSm.setPicThree(Constance.Null2EmptyTrim(obj[11]));
					tblMchtInfSm.setProvCd(Constance.Null2EmptyTrim(obj[12]));
					tblMchtInfSm.setCityCd(Constance.Null2EmptyTrim(obj[13]));
					tblMchtInfSm.setAreaCd(Constance.Null2EmptyTrim(obj[14]));
					tblMchtInfSm.setGroupCD(Constance.Null2EmptyTrim(obj[15]));
					merlist.add(tblMchtInfSm);
				}
			 }
		} catch (DaoException e) {
			e.printStackTrace();
		}
		return merlist;
	}
	
	@Override
	public int sendScanCodeMessageNewAgain(TblMchtInfSm tblMchtInfSm)
			throws ServiceException {
			int resCount = 1;
			String msg="商户已绑卡";
			try {
				String sql = "update apstfr.tbl_mcht_contact s set s.localmchtcd=?,s.outmchtcd=?,s.remark2=?,s.remark3=?,s.remark4=? where s.mchtcd=?";
				String insertSql = "insert into t_wx_audit (MCHT_CD,LOCAL_MCHT,OUT_MCHT,WX_SUBID,STATUS,DT_CREATE,remark1,remark2,remark3) values (?,?,?,?,?,sysdate,?,?,?) ";
				List<Object> parmas=new ArrayList<Object>();
				List<Object> auditParmas=new ArrayList<Object>();
				JSONObject json=new JSONObject();
				String orgCode=null;//机构号
				String groupCd=tblMchtInfSm.getGroupCD();
				if("2".equals(Constance.Null2EmptyTrim(groupCd))){
					logger.info("当前商户为直营商户");
					orgCode=Utils.getConfigValue("org_code_zy");
				}else{
					logger.info("当前商户为非直营商户");
					orgCode=Utils.getConfigValue("org_code");
				}
				json.put("EXT_ORG_NO",orgCode);//机构号
				json.put("TRADE_CODE", "PASM05");//交易代码
				json.put("TX_OUT_CHANNEL", "WZPA");//支付渠道
				json.put("TX_PAY_TYPE", "PA041");//交易类型
				Random r = new Random();
				int randomThr = 10000 + r.nextInt(89999);
				String localMchtCd=String.valueOf(randomThr)+tblMchtInfSm.getId();
				json.put("TX_EXTERNAL_ID",localMchtCd);//本地商户唯一ID
				json.put("TX_NAME", tblMchtInfSm.getName());//名称
				json.put("TX_ALIAS_NAME", tblMchtInfSm.getNameBusi());//简称
				json.put("TX_SERVICE_PHONE", "4006078866");//客服电话
				json.put("TX_CONTACT_MOBILE", tblMchtInfSm.getContactPhone());//联系手机号
				json.put("TX_CATEGORY_ID", tblMchtInfSm.getCategoryId());
				json.put("TX_CONTACT_EMAIL","kf@yjpal.com");//联系邮箱
				json.put("TX_MEMO","");//商户备注
				json.put("TX_ID_CARD_NAME", tblMchtInfSm.getCertif());//身份证姓名
				json.put("TX_ID_CARD_NUM", tblMchtInfSm.getCertifNo());//身份证号码	
				json.put("TX_STORE_ADDRESS", tblMchtInfSm.getRegAddr());//店铺地址
				json.put("TX_ID_CARD_HAND_IMG_URL",tblMchtInfSm.getPicOne());//手持身份证图片
				json.put("TX_STORE_FRONT_IMG_URL",tblMchtInfSm.getPicTwo());//商户门头图片
				json.put("TX_BIZ_LICENSE_IMG_URL",tblMchtInfSm.getPicThree());//营业执照图片
				json.put("TX_PROVINCE", tblMchtInfSm.getProvCd());//省份
				json.put("TX_CITY", tblMchtInfSm.getCityCd());//城市
				json.put("TX_DISTRICT", tblMchtInfSm.getAreaCd());//区县
				json.put("TX_CONTACT_NAME", tblMchtInfSm.getContactName());//联系人
				logger.info("商户入驻请求报文:"+json.toJSONString());
				String settleIn=HttpClientUtil.httpPost(Utils.getConfigValue("url_scanCode"),json);
				logger.info("商户入驻应答报文:"+settleIn);
				JSONObject response=JSONObject.parseObject(settleIn);
				if("00".equals(response.getString("MSG_CODE"))){
					//绑卡
					logger.info("商户入驻成功,进行绑卡操作");
					String outMchtCd=response.getString("SUB_MERCHANT_ID");//入驻商户号
					//处理支付宝
					msg="支付宝入驻";
					String zfb_status="";
					if(response.containsKey("ZFB_STATUS")){
						zfb_status="1";
						msg=msg+"成功";
					}else{
						zfb_status="0";
						msg=msg+"失败";
					}
					//处理微信
					String wxSubidAudit="";//微信子商户号
					msg=msg+",微信入驻";
					String wx_Status="0";
					JSONObject jsonBind=new JSONObject();
					jsonBind.put("EXT_ORG_NO",orgCode);//机构号
					jsonBind.put("TRADE_CODE","PASM05");//交易代码
					jsonBind.put("TX_OUT_CHANNEL", "WZPA");//支付渠道
					jsonBind.put("TX_PAY_TYPE", "PA006");//交易类型
					jsonBind.put("TX_SUB_MERCHANT_ID",outMchtCd);//入驻成功返回的商户号
					jsonBind.put("TX_BANK_CRAD_NO","36610188000159148");//持卡卡号
					jsonBind.put("TX_CARD_HOLDER","德颐支付");//持卡人姓名
					logger.info("商户绑卡请求报文:"+json.toJSONString());
					String bindCard=HttpClientUtil.httpPost(Utils.getConfigValue("url_scanCode"),jsonBind);
					logger.info("商户绑卡应答报文:"+bindCard);
					JSONObject responseCard=JSONObject.parseObject(bindCard);
					if("00".equals(responseCard.getString("MSG_CODE")) && "true".equals(responseCard.getString("BIND_FLAG"))){
						logger.info("商户绑卡成功");
						//尝试去开通微信
						logger.info("尝试去开通微信");
						Map<String,String> wxMap=new HashMap<String, String>();
						wxMap.put("orgCode",orgCode);//机构
						wxMap.put("sub_id",outMchtCd);//入驻商户号
						wxMap.put("transType","PA042");
						String wxResponse=queryEnterInfo(wxMap);
						JSONObject WXresponseJson=JSONObject.parseObject(wxResponse);
						if("00".equals(WXresponseJson.get("MSG_CODE"))){
							if(WXresponseJson.get("WX_SUBID")==null){
								wx_Status="0";//微信子商户入驻失败
								msg=msg+"失败";
							}else{
								wxSubidAudit=WXresponseJson.getString("WX_SUBID");
								if("2".equals(Constance.Null2EmptyTrim(WXresponseJson.get("WX_CONFIG_STATUS")))){
									wx_Status="1";//全部成功
									msg=msg+"成功";
								}else if("1".equals(Constance.Null2EmptyTrim(WXresponseJson.get("WX_CONFIG_STATUS")))){
									wx_Status="2";//部分成功
									msg=msg+"子商户配置未完成,请重新尝试";
								}
								else if(WXresponseJson.get("WX_CONFIG_STATUS")==null){
									wx_Status="3";//微信子商户配置失败
									msg=msg+"子商户配置失败,请尝试重新入驻";
								}						
							}
						}else{
							wx_Status="0";
							msg=msg+"失败,"+WXresponseJson.getString("MSG_TXT");
						}
						logger.info("更新商户入驻信息");
						parmas.add(localMchtCd);
						parmas.add(outMchtCd);
						parmas.add(zfb_status);//支付宝标识
						parmas.add(wx_Status);//微信标识
						parmas.add(tblMchtInfSm.getCategoryId()); //所属行业
						parmas.add(tblMchtInfSm.getId());
						int rows = sqlBaseDao.deleteBySql(sql, parmas);
						if(rows > 0){
							logger.info("记录微信子商户号..");
							auditParmas.add(tblMchtInfSm.getId());
							auditParmas.add(localMchtCd);
							auditParmas.add(outMchtCd);
							auditParmas.add(wxSubidAudit);
							String flag_audit="EE";
							if(!"".equals(wxSubidAudit) && "1".equals(wx_Status)){
								flag_audit="SS";
							}
							auditParmas.add(flag_audit);
							auditParmas.add(tblMchtInfSm.getProvCd()); //省
							auditParmas.add(tblMchtInfSm.getCityCd()); //市
							auditParmas.add(tblMchtInfSm.getAreaCd()); //区
							int effect=sqlBaseDao.deleteBySql(insertSql, auditParmas);
							if(effect > 0){
								baseDao.addSyslog(SysLogType.SCANCODE_HANDLE.getCode(),SysLogType.SCANCODE_HANDLE.getName() ,"","商户【"+tblMchtInfSm.getId()+"】入驻绑卡成功,入驻机构号["+orgCode+"]");
							}
						}
					}else{
						msg="商户绑卡失败,"+responseCard.getString("MSG_TXT");
						resCount = 0;
					}
				}else{
					msg="商户入驻失败,"+response.getString("MSG_TXT");
					resCount = 0;
				}
			logger.info(msg);
			return resCount;
		} catch (Exception e) {
			logger.debug(e.getMessage());
			throw new ServiceException("发送报文失败");
			}			
		}
	
}